<template>
	<view class="person-info-container">
		<view class="header">
			<image class="avatar" src="../../static/avatar/ava1.png" mode="aspectFill" @click="changeAvatar">
			</image>
			<span style="color: white;">点击修改个人头像</span>
		</view>

		<view class="u-demo-block__content">

			<u-form labelPosition="left" :model="model" :rules="rules" ref="form1">
				<u-form-item label="姓名" prop="userInfo.studentName" borderBottom :labelWidth="120">
					<u-input v-model="model.userInfo.studentName" border="none" placeholder="姓名,只能为中文"></u-input>
				</u-form-item>
				<u-form-item label="性别" prop="userInfo.studentSex" borderBottom @click="showSex = true; hideKeyboard()"
					:labelWidth="120">
					<u-input v-model="model.userInfo.studentSex" disabled disabledColor="#ffffff" placeholder="请选择性别"
						border="none"></u-input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="出生日期" prop="userInfo.birthDate" borderBottom :labelWidth="120" borderBottom
					@click="showBirthday = true; hideKeyboard()" v-show="!idShow">
					<u--input v-model="model.userInfo.birthDate" disabled disabledColor="#ffffff" placeholder="请选择生日"
						border="none"></u--input>
				</u-form-item>
				<u-form-item label="身份证号码:" prop="userInfo.idCard" borderBottom :labelWidth="120">
					<u-button type="primary" v-if="idShow" @click="goToRealName">点击实名认证</u-button>

					<u-input v-model="model.userInfo.idCard" border="none" placeholder="点击实名认证"
						v-show="!idShow"></u-input>
				</u-form-item>
				<u-form-item label="手机号" prop="userInfo.studentPhone" borderBottom :labelWidth="120">
					<u-input v-model="model.userInfo.studentPhone" border="none" placeholder="请输入手机号"></u-input>
				</u-form-item>
				<u-form-item label="邮箱" prop="userInfo.studentEmail" borderBottom :labelWidth="120">
					<u-input v-model="model.userInfo.studentEmail" border="none" placeholder="请输入邮箱"></u-input>
				</u-form-item>
				<u-form-item label="备注" borderBottom :labelWidth="120">
					<u-input v-model="model.userInfo.studentNote" border="none" placeholder="请输入备注"></u-input>
				</u-form-item>


			</u-form>
			<u-button type="primary" text="保存修改" customStyle="margin-top: 50px" @click="submit"></u-button>
			<u-button type="success" text="修改实名信息" customStyle="margin-top: 50px" @click="goToRealName"
				v-if="!idShow"></u-button>

			<u-action-sheet :show="showSex" :actions="actions" title="请选择性别" @close="showSex = false"
				@select="sexSelect">
			</u-action-sheet>
			<u-datetime-picker :show="showBirthday" :value="birthday" mode="date" closeOnClickOverlay
				 @confirm="birthdayConfirm" @cancel="birthdayClose"
				@close="birthdayClose"></u-datetime-picker>

			<u-notify ref="uNotify"></u-notify>
		</view>
		<!-- 更换头像的弹出层 -->
		<u-popup :safeAreaInsetBottom="true" :safeAreaInsetTop="true" :mode="popupData.mode" :show="poupShow"
			:round="popupData.round" :overlay="popupData.overlay" :borderRadius="popupData.borderRadius"
			:closeable="popupData.closeable" :closeOnClickOverlay="popupData.closeOnClickOverlay" @close="close"
			@open="open" >
			<view class="u-popup-slot" :style="{
							width: ['bottom', 'top'].includes(popupData.mode) ? '750rpx' : '300px',
							marginTop: ['left', 'right'].includes(popupData.mode) ? '680rpx' : '0',
							
						}">
				<h3 style="text-align: center;">请上传头像</h3>
				<view class="u-demo-block__content">
					<view class="u-page__upload-item">
						<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="6" multiple
							:maxCount="1" width="300" height="300" :previewFullImage="false">
						</u-upload>
						<u-button type="primary" @click="submitUpload()">确认修改</u-button>
					</view>
				</view>
				
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		checkStudentInfo,
		saveStuChange
	} from '@/api/student.js'

	export default {
		data() {
			return {
				baseUrl: 'http://localhost:8001',
				user: {
					studentId: 5
				},
				model: {
					userInfo: {
						studentName: '',
						studentSex: '',
						birthDate: '',
						idCard: '',
						studentPhone: '',
						studentEmail: '',
						studentNote: ''

					},

				},
				showBirthday: false,
				showSex: false,
				idShow: false, //实名认证按钮显示
				birthday: Number(new Date()),
				actions: [{
						name: '男',
					},
					{
						name: '女',
					},
					{
						name: '保密',
					},
				],
				list: [{
					notifyData: {
						message: '修改成功',
						type: 'success',
						color: '#ffffff',
						bgColor: '',
						fontSize: 15,
						duration: 3000,
						safeAreaInsetTop: false
					},

				}, {
					notifyData: {
						message: '修改失败',
						type: 'error',
						color: '#ffffff',
						bgColor: '',
						fontSize: 14,
						duration: 3000,
						safeAreaInsetTop: false
					},


				}, ],
				rules: {
					'userInfo.studentName': [{
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							return uni.$u.test.chinese(value);
						},
						message: "姓名必须为中文",

						trigger: ["change", "blur"],
					}],

					'userInfo.studentSex': {
						type: 'string',
						max: 2,
						required: true,
						message: '请选择男或女',
						trigger: ['blur', 'change']
					},
					'userInfo.studentPhone': [{
							required: true,
							message: '请输入手机号',
							trigger: 'blur'
						},
						{
							validator: (rule, value, callback) => {
								const phoneReg = /^1[3-9]\d{9}$/; // 手机号正则表达式
								if (!phoneReg.test(value)) {
									callback(new Error('请输入正确的手机号格式'));
								} else {
									callback();
								}
							},
							trigger: 'blur'
						}
					],


					'userInfo.studentEmail': [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: (rule, value, callback) => {
								const emailReg = /^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
								if (!emailReg.test(value)) {
									callback(new Error('请输入正确的邮箱格式'));
								} else {
									callback();
								}
							},
							trigger: 'blur'
						}
					]
				},
				popupData: {
					overlay: true,
					mode: 'center',
					borderRadius: '',
					closeable: true,
					closeOnClickOverlay: true
				},
				poupShow: false,
				fileList: [],


			}
		},
		onLoad() {
			uni.$on('refreshPersonInfo', () => {
				this.queryUserInfo();
			});
		},
		onUnload() {
			uni.$off('refreshPersonInfo');
		},
		created() {
			this.queryUserInfo();
		},
		methods: {
			changeAvatar() {
				console.log("修改头像");
				this.fileList=[],
				this.poupShow = true;
				
			},
			open(){},
			close() {
				this.poupShow = false

			},
			async queryUserInfo() {
			  try {
			    
			    const url = `${this.baseUrl}/student/checkStudentInfo`;
			    
			    const res = await uni.request({
			      url: url,
			      method: 'GET',
			      data: {
			        studentId: this.user.studentId
			      }
			    });
		
			    if (res.statusCode === 200) {
			      let stu = res.data.data.student;
			      
			      
			      if (stu.birthDate != null) {
			        stu.birthDate = stu.birthDate.substring(0, 10);
			      }
			      this.model.userInfo = stu;
			      this.idShow = (this.model.userInfo.idCard == null);
				  
			    } else {
			      throw new Error(`请求失败，状态码: ${res.statusCode}`);
			    }
			  } catch (error) {
			    console.error('获取学生信息失败:', error);
			    uni.showToast({
			      title: '获取信息失败，请稍后重试',
			      icon: 'none'
			    });
			  }
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			sexSelect(e) {
				this.model.userInfo.studentSex = e.name
				this.$refs.form1.validateField('userInfo.sex')
			},
			async submit() {
				const url = `${this.baseUrl}/student/saveStuChange`;
				console.log(url);
				try{
					await this.$refs.form1.validate();
					let birthDate = this.model.userInfo.birthDate;
					    if (birthDate && !birthDate.includes('T')) {
					      birthDate = `${birthDate}T00:00:00`;
					    }
						 const stu = {
						      ...this.model.userInfo,
						      birthDate: birthDate
						    };
							 
							 const res = await uni.request({
							   url: url,
							   method: 'PUT',
							   data: stu
							 });
							    console.log(res);
								if (res.data.data.student) {
								      this.openNotify(this.list[0]);
								    } else {
								      this.openNotify(this.list[1]);
								    }
								    
								    // 更新用户信息
								    this.queryUserInfo();
				}catch(errors){
					console.log(errors);
					    uni.$u.toast("保存修改出错，请稍后重试");
				}
				
			},

			birthdayClose() {
				this.showBirthday = false;
			},
			birthdayConfirm(e) {

				this.showBirthday = false
				const date = new Date(e.value);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				this.model.userInfo.birthDate = `${year}-${month}-${day}`;
			},
			//跳转实名认证页面
			goToRealName() {
				uni.navigateTo({
					url: '/pages/real-name/real-name'
				});
			},
			openNotify(params) {
				if (this.$refs.uNotify) {
					this.$refs.uNotify.show({
						...params.notifyData
					});
				} else {
					console.error("uNotify组件未正确加载");
					uni.$u.toast(params.notifyData.message);
				}
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1);
				this.localFiles.splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				let lists = [].concat(event.file);
			
				// 清空之前选择的图片（因为maxCount=1）
				this.fileList = [];
				this.localFiles = [];
			
				lists.forEach(item => {
					// 保存到文件列表（显示缩略图，但标记为待上传）
					this.fileList.push({
						url: item.url,
						status: 'waiting',
						message: '待上传'
					});
			
					// 保存本地路径，用于后续上传
					this.localFiles.push(item.url);
				});
			
				this.uploadResult = ''; // 清除之前的结果提示
			
			},
			async submitUpload() {
				 if (this.localFiles.length === 0) {
				        uni.showToast({
				            title: '请先选择身份证照片',
				            icon: 'none'
				        });
				        return;
				    }
				
				    this.isUploading = true;
				    this.uploadResult = '';
				
				    try {
				        // 获取本地文件
				        const localUrl = this.localFiles[0];
				        const url = `${this.baseUrl}/student/changeAvatar`;
				        // 使用uni.uploadFile上传文件
				        const uploadTask = uni.uploadFile({
							
				            url: url, 
				            filePath: localUrl,
				            name: 'file', 
				            formData: {
				                studentId: this.user.studentId 
				            },
				            success: (res) => {
								
				                const response = JSON.parse(res.data.data);
				                console.log(response);
				                if (response.code === 200) { 
				
				                    // 更新文件状态
				                    this.fileList[0] = {
				                        ...this.fileList[0],
				                        status: 'success',
				                        message: '修改头像成功'
				                    };
				
				                    this.uploadResult = '修改头像成功';
				                    uni.showToast({
				                        title: '修改头像成功',
				                        icon: 'success'
				                    });
									this.poupShow=false;
				
				
				                } else {
									uni.showToast({
									    title: '修改头像失败',
									    icon: 'error'
									});
				                    
				                }
				            },
				            fail: (err) => {
				                console.error('上传失败:', err);
				                throw new Error('网络错误，请重试');
				            }
				        });
				        
				        
				        
				} catch (error) {
					console.error('实名认证失败:', error);
					this.uploadResult = error.message || '实名认证失败，请重试';
			
					// 更新文件状态
					if (this.fileList.length > 0) {
						this.fileList[0] = {
							...this.fileList[0],
							status: 'fail',
							message: '识别失败'
						};
					}
				} finally {
					this.isUploading = false;
				}
			},
		}
	}
</script>



<style lang="scss">
	.person-info-container {
		padding: 40rpx;
		background-color: #f8f8f8;
		min-height: 95vh;
		box-sizing: border-box;

		.header {
			font-size: 28rpx;
			padding-right: 20rpx;
			background-image: radial-gradient(circle 248px at center, #16d9e3 0%, #30c7ec 47%, #46aef7 100%);
			height: 20vh;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.avatar {
				width: 160rpx;
				height: 160rpx;
				border-radius: 50%;
				margin-bottom: 20rpx;
				border: 2rpx solid #FFFFFF;
				box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

			}
		}
	}
</style>